//
//  MimikViewController.m
//  Mimik
//
//  Created by Mikkel Gravgaard on 15/12/09.
//  Copyright __MyCompanyName__ 2009. All rights reserved.
//

#import "MimikViewController.h"

@implementation MimikViewController

@synthesize scoreLabel, game;

float const PLAY_DELAY = 0.15;

#define N_BUTTONS 3
#define BUTTON_ZOOM 1.2

// Here could be more button features
struct buttonStruct {
	UIImage *imgDeselected;
	UIImage *imgSelected;
	UIButton *button;
	AVAudioPlayer *player;
} buttons[N_BUTTONS]; 

- (id)initWithCoder:(NSCoder *)coder {
	
	if (self = [super initWithCoder:coder]) {
		[self setUpView];
	}
	return self;
}

- (void)setUpView {
	NSString *imgFilesDeselected[] = {
		@"red1.png",@"green1.png",@"blue1.png"
	};

	NSString *imgFilesSelected[] = {
		@"red2.png",@"green2.png",@"blue2.png"
	};
	
	NSString *soundFiles[] = {
		@"sound1",@"sound2",@"sound3"
	};
	
	CGFloat button_delta = (self.view.bounds.size.height * 0.85)/N_BUTTONS;
	
	for(NSInteger i=0; i<N_BUTTONS;i++){
		UIImage *imgDeselected = [UIImage imageNamed:imgFilesDeselected[i]];
		UIImage *imgSelected = [UIImage imageNamed:imgFilesSelected[i]];		
		CGRect frame = CGRectMake(0.0f, 0.0f, [imgDeselected size].width, [imgDeselected size].height);
		
		frame.origin.y = button_delta*i+button_delta/2; // defined by screen height and the button's index
      frame.origin.x = self.view.center.x-frame.size.width/2; // defined by screen center and frame width      
		
      UIButton *btn = [[UIButton alloc] initWithFrame:frame];
		[btn setImage:imgDeselected forState:UIControlStateNormal];
		[btn setImage:imgSelected forState:UIControlStateHighlighted];

		[btn addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchDown];
		btn.enabled=NO;
		NSString *path = soundFiles[i];
		NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: [[NSBundle mainBundle] pathForResource:path ofType:@"wav"]];
		buttons[i].button = btn;
		buttons[i].imgDeselected = imgSelected;
		buttons[i].imgSelected = imgSelected;
		buttons[i].player = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:nil];
		[fileURL release];		
		[self.view addSubview:btn];
	}
	
	scoreLabel = [[[UICenteredLabel alloc] init] autorelease];
	[scoreLabel setText:@"Here be score?"];
	[scoreLabel sizeToFit];
	scoreLabel.center = self.view.center;
	CGRect r = [scoreLabel frame];
	r.origin.y = (self.view.bounds.size.height-scoreLabel.bounds.size.height*2);
	[scoreLabel setFrame:r];
	[self.view addSubview:scoreLabel];
	
}

- (NSInteger)getNumberFromButton:(UIButton *)btn
{
	NSInteger i;
	for(i=0; i<N_BUTTONS;i++){
		if(btn==buttons[i].button) break;
	}
	return i;
}

- (void)showChallenge:(NSArray *)numbers{
   [scoreLabel setText:[NSString stringWithFormat:@"Score: %d",[game score]]];
	[self toggleButtons:YES];
	animButtons = [[NSMutableArray alloc] initWithCapacity:numbers.count];
	for(NSNumber *number in numbers){
		// insert button in array
		[animButtons addObject:buttons[[number integerValue]].button];
	}
	btnEnumerator = [[animButtons objectEnumerator] retain];
	myTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(startAnim) userInfo:nil repeats:NO];
}

- (void)startAnim{
	[self animateNextButton:nil finished:[NSNumber numberWithBool:YES] context:nil];
}

- (void)animateNextButton:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context{
	UIButton* btn;
	if(btn = [btnEnumerator nextObject]){  
		NSInteger btnNumber = [self getNumberFromButton:btn];
		[self play:btnNumber];
		[self animateButton:btn];
	} else {
		[btnEnumerator release];
		[self toggleButtons:YES];
	}
}

- (void)animateButton:(UIButton *)btn{
	[UIView beginAnimations:nil context:btn];
	[UIView setAnimationDuration:PLAY_DELAY];
	btn.transform = CGAffineTransformMakeScale(BUTTON_ZOOM, BUTTON_ZOOM);
	
	[UIView setAnimationDelegate:self];
	[UIView setAnimationDidStopSelector:@selector(growAnimationDidStop:finished:context:)];
	[UIView commitAnimations];
	
}

- (void)growAnimationDidStop:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context{
	UIButton* btn = (UIButton *)context;
	[UIView beginAnimations:nil context:NULL];
	[UIView setAnimationDuration:PLAY_DELAY];
	btn.transform = CGAffineTransformMakeScale(1, 1);
	[UIView setAnimationDelegate:self];
	[UIView setAnimationDidStopSelector:@selector(animateNextButton:finished:context:)];
	[UIView commitAnimations];
	[btn release];
}

-(void)newGame:(id)sender
{
	[self toggleButtons:NO];
	[game newGame];
}

-(void)play:(NSInteger) btnNumber{
	AVAudioPlayer *player = buttons[btnNumber].player;
	[player pause];
	player.currentTime=0;
	[player play];
}

- (void)buttonAction:(id)sender{
	NSInteger btnNumber = [self getNumberFromButton:sender];
	[game respond:btnNumber];
	[self play:btnNumber];
}

-(void)gameOver{
	[self toggleButtons:NO];
	newGameButton.enabled=YES;
	[scoreLabel setText:[NSString stringWithFormat:@"Game over! Score: %d",[game score]]];
	[scoreLabel sizeToFit];
}

-(void)toggleButtons:(Boolean) enable{
	newGameButton.enabled=NO; 
	for(NSInteger i=0;i<N_BUTTONS;i++){
		buttons[i].button.enabled=enable;
	}
}

/*
// The designated initializer. Override to perform setup that is required before the view is loaded.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        // Custom initialization
    }
    return self;
}
*/

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
}
*/


/*
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
}
*/


/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}


- (void)dealloc {
	[game dealloc];
    [super dealloc];
}

@end
